

<?php

require_once LIBRARIES_ENTITIES_DATABASE;
require_once LIBRARIES_ENTITIES_ORDERS;
require_once LIBRARIES_ENTITIES_ORDERDETAIL;
require_once LIBRARIES_TOOLS_UTILITY;


require_once LIBRARIES_TOOLS_XTEMPLATE;
require_once LIBRARIES_TOOLS_PAGERBACKEND;

class OrdersController {

    //put your code here
    public function invoke() {

        // function list
        $groupFunctions = $_SESSION['groupFunctions'];

        $userID = $_SESSION["session"]["sUserID"];

        // acttion
        $action = '';
        if (isset($_POST['hdAction'])) {
            $action = $_POST['hdAction'];
        }


        // task
        $task = '';
        if (isset($_GET['task'])) {
            $task = $_GET['task'];
        }

        // tổng số dòng muốn hiển thị
        $rowToView = 10;
        if (isset($_POST["limit"])) {
            $rowToView = $_POST["limit"];
        }


        // ACTION
        if ($action == 'finish') {
            $result = $this->updateOrderStatus($_POST['hdOrderID'], 1);
        } else if ($action == 'notFinish') {
            $result = $this->updateOrderStatus($_POST['hdOrderID'], 0);
        } else if ($action == 'remove') {

            // mảng danh sách giá trị id
            $values = $_POST["cid"];

            $result = $this->removeOrder($values);
        }


        // TASK
        if ($task == 'view') {

            // check view permission
            if (Utility::checkPermission('view', $groupFunctions, ORDER_MANAGEMENT)) {

                $viewFile = ADMIN_COM . DS . 'com_orders' . DS . 'views' . DS . 'order_list.html';
                $xtemplate = new XTemplate($viewFile);

                // check delete button
                if (Utility::checkPermission('delete', $groupFunctions, ORDER_MANAGEMENT)) {
                    $xtemplate->parse('main.delete_button');
                }


                // chỉ mục của checkbox
                $indexCheckBox = 1;

                // page hiện tại đang xem
                $rurrentPage = 1;
                if (isset($_POST["page"])) {
                    $rurrentPage = $_POST["page"];
                }


                // chỉ mục (số thứ tự của bài viết) bài viết
                $index = 1;



                $orders = $this->getOrders();

                // tải đối tượng phân trang
                $pager = PagerBackEnd::getPagerData(count($orders), $rowToView, $rurrentPage);


                if ($orders != null) {

                    $indexCheckBox = 1;

                    foreach ($orders as $order) {

                        if ($index > $pager->offset && $index <= $pager->limit) {

                            // order detal
                            $orderDetail = $this->getOrderDetailByOrderID($order->getID());

                            // total of an order
                            $totalOfOrder = 0;

                            if ($orderDetail != null) {
                                // calculate total
                                foreach ($orderDetail as $value) {
                                    $total = $value->getPrice() * $value->getQuantity();
                                    $totalOfOrder += $total;
                                }
                            }


                            // index of order list
                            $xtemplate->assign('INDEX', $index);

                            // index of checkbox
                            // start 1 of each page
                            $xtemplate->assign('INDEX_CHECKBOX', $indexCheckBox);

                            // order id
                            $xtemplate->assign('ORDER_ID', $order->getID());

                            // order date
                            $xtemplate->assign('ORDER_DATE', Utility::formatDateTimeToView($order->getCreatedDate()));

                            // customer name
                            $xtemplate->assign('CUSTOMER_NAME', $order->getCustomer()->getName());

                            // customer phone
                            $xtemplate->assign('CUSTOMER_PHONE', $order->getCustomer()->getPhone());

                            // customer email
                            $xtemplate->assign('CUSTOMER_EMAIL', $order->getCustomer()->getEmail());

                            // total 
                            $xtemplate->assign('TOTAL', Utility::formatToCurrencyString($totalOfOrder));

                            // gender
                            if ($order->getCustomer()->getGender() == 1) {
                                $xtemplate->assign('CUSTOMER_GENDER', 'Nam');
                            } else {
                                $xtemplate->assign('CUSTOMER_GENDER', 'Nữ');
                            }

                            // status
                            if ($order->getStatus() == 0) {
                                $xtemplate->parse('main.order_list.status_waiting');
                            } else {
                                $xtemplate->parse('main.order_list.status_finished');
                            }

                            // description
                            $xtemplate->assign('ORDER_DESCRIPTION', $order->getDescription());


                            // show each of list
                            $xtemplate->parse('main.order_list');

                            $indexCheckBox++;
                        }
                        $index++;
                    }
                }


                // danh sách chọn số dòng hiển thị
                $xtemplate->assign('LIMIT_LIST', Utility::getLimitList($rowToView));

                // tổng số dòng hiển thị
                $xtemplate->assign('ROW_TO_VIEW', $rowToView);

                // trang hiện tại
                $xtemplate->assign('CURRENT_PAGE', $rurrentPage);

                // tổng số trang có được
                $xtemplate->assign('AMOUNT_OF_PAGE', $pager->numPages);

                // định dạng phân trang html
                $xtemplate->assign('PAGING_HTML', $pager->paging);

                $xtemplate->parse('main');
                $xtemplate->out('main');
            } else {
                echo ERROR_PERMISSION;
            }
        }
        // nếu task là edit thì include trang thêm vào
        else if ($task == 'edit') {
            // if exist orderID, then show detail
            if (isset($_GET['orderID'])) {

                // order id
                $orderID = $_GET['orderID'];

                // get order
                $order = $this->getOrderByID($orderID);



                if ($order != null) {

                    $viewFile = ADMIN_COM . DS . 'com_orders' . DS . 'views' . DS . 'order_edit.html';
                    $xtemplate = new XTemplate($viewFile);



                    // get order detail
                    $orderDetail = $this->getOrderDetailByOrderID($orderID);

                    // total of order
                    $total = 0;

                    if (count($orderDetail) > 0) {
                        foreach ($orderDetail as $value) {

                            $totalPrice = $value->getQuantity() * $value->getPrice();

                            $xtemplate->assign('ITEM_IMAGE', $value->getItem()->getImage());
                            $xtemplate->assign('ITEM_NAME', $value->getItem()->getName());
                            $xtemplate->assign('ITEM_QUANTITY', $value->getQuantity());
                            $xtemplate->assign('ITEM_PRICE', Utility::formatToCurrencyString($value->getPrice()));
                            $xtemplate->assign('TOTAL_PRICE', Utility::formatToCurrencyString($totalPrice));

                            if ($value->getItemPropertyID() != '') {
                                $xtemplate->assign('ITEM_PROPERTY', $value->getItemProperty()->getValue());
                            }

                            $xtemplate->parse('main.item_list');

                            $total += $totalPrice;
                        }
                    }

                    $xtemplate->assign('TOTAL', $total);
                    $xtemplate->assign('ORDER_ID', $order->getID());
                    $xtemplate->assign('ORDER_DATE', Utility::formatDateTimeToView($order->getCreatedDate()));
                    $xtemplate->assign('ORDER_DESCRIPTION', $order->getDescription());

                    $xtemplate->assign('CUSTOMER_NAME', $order->getCustomer()->getName());
                    if ($order->getCustomer()->getProvinceID() != '') {
                        $xtemplate->assign('CUSTOMER_PROVINCE', $order->getCustomer()->getProvince()->getName());
                    }
                    $xtemplate->assign('CUSTOMER_PHONE', $order->getCustomer()->getPhone());
                    $xtemplate->assign('CUSTOMER_ADDRESS', $order->getCustomer()->getAddress());

                    if ($order->getCustomer()->getGender() == 0) {
                        $xtemplate->assign('CUSTOMER_GENDER', 'Nữ');
                    } else {
                        $xtemplate->assign('CUSTOMER_GENDER', 'Nam');
                    }

                    if ($order->getStatus() == 0) {
                        $xtemplate->parse('main.finish_button');
                    } else {
                        $xtemplate->parse('main.notfinish_button');
                    }
                    $xtemplate->parse('main');
                    $xtemplate->out('main');
                }
            } else {
                Utility::redirect('.?com=com_orders&task=view');
            }
        }
    }

    // get list of order
    private function getOrderByID($orderID) {
        $db = new Database();
        try {
            $order = new Orders();
            $order->setID($orderID);
            $result = $order->getByID($db);
            $db->submitChanges();
            return $result;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

    // get list of order
    private function getOrders() {
        $db = new Database();
        try {
            $order = new Orders();
            $result = $order->getList($db);
            $db->submitChanges();
            return $result;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

    // get detail of an order
    private function getOrderDetailByOrderID($orderID) {
        $db = new Database();
        try {
            $orderDetail = new OrderDetail();
            $orderDetail->setOrderID($orderID);
            $result = $orderDetail->getListByOrderID($db);
            $db->submitChanges();
            return $result;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

    private function updateOrderStatus($orderID, $status) {
        $db = new Database();
        try {
            $order = new Orders();
            $order->setID($orderID);
            $order->setStatus($status);
            $order->updateStatus($db);
            $db->submitChanges();
            return OK;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

    private function removeOrder($values) {
        $db = new Database();
        try {
            for ($i = 0; $i < count($values); $i++) {
                $order = new Orders();
                $order->setID($values[$i]);
                $order->delete($db);
            }
            $db->submitChanges();
            return OK;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            exit();
        }
    }

}
?>
